package com.zjj.sc.movie.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zjj.sc.movie.dto.User;

@RestController
public class ConsumerMovieRibbonController {
	
	private static final Logger logger = LoggerFactory.getLogger(ConsumerMovieRibbonController.class);
	
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	LoadBalancerClient loadBalanceClient;

	@Value("${user.userServiceUrl}")
	private String userServiceUrl;
	
	
	@HystrixCommand(fallbackMethod = "findByIdFallback")
	@GetMapping("/user/{id}")
	public User findById(@PathVariable Long id) {
		System.out.println("--------get user userServiceUrl = " + userServiceUrl + "-------");
		System.out.println("--------get user id = " + id + "-------");
		return restTemplate.getForObject("http://microservice-4-provider-user/" + id, User.class);
	}
	
	@GetMapping("/instance")
	public void logInstance() {
		ServiceInstance instance = this.loadBalanceClient.choose("microservice-4-provider-user");
		logger.info("{}:{}:{}",instance.getServiceId(),instance.getHost(),instance.getPort());
	}
	
	public User findByIdFallback(Long id) {
		User user = new User();
		user.setId(-1L);
		user.setName("zjj");
		return user;
	}

}
